// 云函数入口文件
const cloud = require('wx-server-sdk')

const TcbRouter = require('tcb-router')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

const teacherCollection = db.collection('teacher')

const MAX_LIMIT = 50

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })

  app.router('fetchList', async (ctx, next) => {
    ctx.body = await teacherCollection.limit(MAX_LIMIT).get()
      .then((res) => {
        const teacherList = []
        const allItems = res.data
        for (let item of allItems) {
          teacherList.push({
            _id: item._id,
            surname: item.surname,
            gender: item.gender,
            school: item.school,
            grade: item.grade,
            image: item.images[0],
            scope: item.scope,
            introduction: item.introduction
          })
        }
        return teacherList
      })
  })

  app.router('fetch', async (ctx, next) => {
    ctx.body = await teacherCollection.doc(event._id).get()
      .then((res) => {
        return res.data
      })
  })

  app.router('update', async (ctx, next) => {
    ctx.body = await teacherCollection.doc(event._id).update({
      data: event.data
    }).then((res) => {
      return res
    })
  })

  app.router('add', async (ctx, next) => {
    ctx.body = await teacherCollection.add({
      data: event.data
    }).then((res) => {
      return res
    })
  })

  return app.serve()
}